package com.yupi.yupicturebackend.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yupi.yupicturebackend.model.entity.GameSession;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 游戏会话Mapper
 *
 * @author yupi
 */
@Mapper
public interface GameSessionMapper extends BaseMapper<GameSession> {

    /**
     * 根据用户ID查询游戏会话
     *
     * @param userId 用户ID
     * @param limit 限制数量
     * @return 游戏会话列表
     */
    @Select("SELECT * FROM game_session WHERE userId = #{userId} AND isDelete = 0 ORDER BY createTime DESC LIMIT #{limit}")
    List<GameSession> selectByUserId(@Param("userId") Long userId, @Param("limit") Integer limit);

    /**
     * 根据游戏类型查询会话
     *
     * @param gameType 游戏类型
     * @param limit 限制数量
     * @return 游戏会话列表
     */
    @Select("SELECT * FROM game_session WHERE gameType = #{gameType} AND isDelete = 0 ORDER BY createTime DESC LIMIT #{limit}")
    List<GameSession> selectByGameType(@Param("gameType") String gameType, @Param("limit") Integer limit);

    /**
     * 根据状态查询会话
     *
     * @param status 游戏状态
     * @param limit 限制数量
     * @return 游戏会话列表
     */
    @Select("SELECT * FROM game_session WHERE status = #{status} AND isDelete = 0 ORDER BY createTime DESC LIMIT #{limit}")
    List<GameSession> selectByStatus(@Param("status") String status, @Param("limit") Integer limit);

    /**
     * 查询用户正在进行的游戏
     *
     * @param userId 用户ID
     * @return 正在进行的游戏列表
     */
    @Select("SELECT * FROM game_session WHERE userId = #{userId} AND status IN ('created', 'playing', 'paused') AND isDelete = 0 ORDER BY createTime DESC")
    List<GameSession> selectActiveGamesByUserId(@Param("userId") Long userId);

    /**
     * 查询用户已完成的游戏
     *
     * @param userId 用户ID
     * @param limit 限制数量
     * @return 已完成的游戏列表
     */
    @Select("SELECT * FROM game_session WHERE userId = #{userId} AND status = 'completed' AND isDelete = 0 ORDER BY completionTime DESC LIMIT #{limit}")
    List<GameSession> selectCompletedGamesByUserId(@Param("userId") Long userId, @Param("limit") Integer limit);

    /**
     * 统计用户游戏次数
     *
     * @param userId 用户ID
     * @param gameType 游戏类型（可选）
     * @return 游戏次数
     */
    @Select("<script>" +
            "SELECT COUNT(*) FROM game_session WHERE userId = #{userId} AND isDelete = 0" +
            "<if test='gameType != null'> AND gameType = #{gameType}</if>" +
            "</script>")
    Long countGamesByUserId(@Param("userId") Long userId, @Param("gameType") String gameType);

    /**
     * 统计用户完成的游戏次数
     *
     * @param userId 用户ID
     * @param gameType 游戏类型（可选）
     * @return 完成次数
     */
    @Select("<script>" +
            "SELECT COUNT(*) FROM game_session WHERE userId = #{userId} AND status = 'completed' AND isDelete = 0" +
            "<if test='gameType != null'> AND gameType = #{gameType}</if>" +
            "</script>")
    Long countCompletedGamesByUserId(@Param("userId") Long userId, @Param("gameType") String gameType);

    /**
     * 查询用户最高分数
     *
     * @param userId 用户ID
     * @param gameType 游戏类型
     * @param difficulty 难度等级（可选）
     * @return 最高分数
     */
    @Select("<script>" +
            "SELECT MAX(currentScore) FROM game_session WHERE userId = #{userId} AND gameType = #{gameType} AND status = 'completed' AND isDelete = 0" +
            "<if test='difficulty != null'> AND difficulty = #{difficulty}</if>" +
            "</script>")
    Integer selectMaxScoreByUser(@Param("userId") Long userId, @Param("gameType") String gameType, @Param("difficulty") String difficulty);

    /**
     * 查询用户平均分数
     *
     * @param userId 用户ID
     * @param gameType 游戏类型
     * @return 平均分数
     */
    @Select("SELECT AVG(currentScore) FROM game_session WHERE userId = #{userId} AND gameType = #{gameType} AND status = 'completed' AND isDelete = 0")
    Double selectAvgScoreByUser(@Param("userId") Long userId, @Param("gameType") String gameType);

    /**
     * 查询用户总游戏时长
     *
     * @param userId 用户ID
     * @return 总时长（秒）
     */
    @Select("SELECT SUM(duration) FROM game_session WHERE userId = #{userId} AND status = 'completed' AND isDelete = 0")
    Long selectTotalPlayTimeByUser(@Param("userId") Long userId);

    /**
     * 统计各游戏类型的游戏次数
     *
     * @return 游戏类型统计
     */
    @Select("SELECT gameType, COUNT(*) as count FROM game_session WHERE isDelete = 0 GROUP BY gameType ORDER BY count DESC")
    List<java.util.Map<String, Object>> countByGameType();

    /**
     * 统计各难度等级的游戏次数
     *
     * @param gameType 游戏类型
     * @return 难度统计
     */
    @Select("SELECT difficulty, COUNT(*) as count FROM game_session WHERE gameType = #{gameType} AND isDelete = 0 GROUP BY difficulty ORDER BY count DESC")
    List<java.util.Map<String, Object>> countByDifficulty(@Param("gameType") String gameType);

    /**
     * 查询高分游戏记录
     *
     * @param gameType 游戏类型
     * @param difficulty 难度等级
     * @param limit 限制数量
     * @return 高分记录列表
     */
    @Select("SELECT * FROM game_session WHERE gameType = #{gameType} AND difficulty = #{difficulty} AND status = 'completed' AND isDelete = 0 ORDER BY currentScore DESC LIMIT #{limit}")
    List<GameSession> selectHighScoreGames(@Param("gameType") String gameType, @Param("difficulty") String difficulty, @Param("limit") Integer limit);

    /**
     * 更新游戏状态
     *
     * @param sessionId 会话ID
     * @param status 新状态
     * @return 更新行数
     */
    @Update("UPDATE game_session SET status = #{status}, updateTime = NOW() WHERE sessionId = #{sessionId}")
    int updateGameStatus(@Param("sessionId") String sessionId, @Param("status") String status);

    /**
     * 更新游戏分数和进度
     *
     * @param sessionId 会话ID
     * @param score 当前分数
     * @param progress 游戏进度
     * @return 更新行数
     */
    @Update("UPDATE game_session SET currentScore = #{score}, progress = #{progress}, updateTime = NOW() WHERE sessionId = #{sessionId}")
    int updateGameProgress(@Param("sessionId") String sessionId, @Param("score") Integer score, @Param("progress") Integer progress);

    /**
     * 完成游戏
     *
     * @param sessionId 会话ID
     * @param finalScore 最终分数
     * @param duration 游戏时长
     * @param gameResult 游戏结果
     * @return 更新行数
     */
    @Update("UPDATE game_session SET status = 'completed', completed = 1, currentScore = #{finalScore}, duration = #{duration}, gameResult = #{gameResult}, completionTime = NOW(), endTime = NOW(), updateTime = NOW() WHERE sessionId = #{sessionId}")
    int completeGame(@Param("sessionId") String sessionId, @Param("finalScore") Integer finalScore, @Param("duration") Integer duration, @Param("gameResult") String gameResult);
}
